"use client";
import { DepositsRep } from "@/api/user";
import { Pagination } from "@/types";
import { server } from "@/utils/client";
import { useSetState } from "ahooks";
import { InfiniteScroll } from "antd-mobile";
import { useTranslations } from "next-intl";
import { useRef } from "react";
import Message from "./components/Message";

type Params = { current_page: number; page_size: number; use_page: boolean };

const getTransactionsApi = async (data: Params) => {
    return server.post<DepositsRep[]>({
        url: "/v1/api/user/user_transactions",
        data: data,
    });
};

const Bouns = () => {
    const t = useTranslations();
    const params = useRef({ current_page: 0, page_size: 20, use_page: true });
    const [sourceData, setSourceData] = useSetState<{
        list: DepositsRep[];
        page: Partial<Pagination>;
    }>({ list: [], page: { is_end: false } });
    const getDepositsData = async () => {
        return getTransactionsApi(params.current).then((res) => {
            const newData = res.data.map((item) => {
                return {
                    ...item,
                    title: t(
                        `${item.type === 16 ? "activityType" : "bonusType"}.${item.type === 16 ? item.sub_type : item.type}`
                    ),
                };
            });
            setSourceData((value) => ({ page: res.page, list: [...value.list, ...newData] }));
            return res;
        });
    };
    const loadMore = async () => {
        params.current.current_page += 1;
        await getDepositsData();
        return Promise.resolve();
    };
    return (
        <>
            <Message data={sourceData.list} />
            <InfiniteScroll loadMore={loadMore} hasMore={!sourceData.page.is_end!} />
        </>
    );
};

export default Bouns;
